package com.lenovo.agricultureServer.http;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.UnknownHostException;
import java.util.Map;

import android.content.Context;
import android.util.Log;

import com.lenovo.agricultureServer.http.action.BaseAction;
import com.lenovo.agricultureServer.http.action.ControlAction;
import com.lenovo.agricultureServer.http.action.FindPwdAction;
import com.lenovo.agricultureServer.http.action.GetConfigAction;
import com.lenovo.agricultureServer.http.action.GetControllerStatusAction;
import com.lenovo.agricultureServer.http.action.GetSensorAction;
import com.lenovo.agricultureServer.http.action.LoginAction;
import com.lenovo.agricultureServer.http.action.RegisterAction;
import com.lenovo.agricultureServer.http.action.SetConfigAction;

public class JasonSoapHttpServer extends NanoHTTPD {
	private static String TAG = "JasonHttpServer";
	private Context context;

	public JasonSoapHttpServer(String ip, int port, Context context) throws UnknownHostException {
		super(ip, port);
		this.context = context;
	}

	@Override
	public Response serve(IHTTPSession session) 
	{
		Log.i(TAG, "enter serve method");
		String httpResp = "Can't find action";
		// 解析http body
		String strBody = "";
		if(session.getMethod() == Method.POST){
			strBody = parsebody(session);
		}
		String strUrl = session.getUri();
		Log.i(TAG, "Http url:"+strUrl+", body:"+strBody);

		//解析出请求名称和协议类型
		String actionName = "";
		String actionType = "";
		String tmpArray[] = strUrl.split("/");
		for(int i=0; i<tmpArray.length; i++)
		{
			String str = tmpArray[i];
			if(str.equals("type")){
				actionType = tmpArray[i+1];
			}
			if(str.equals("action")){
				actionName = tmpArray[i+1];
			}
		}
		Log.i(TAG, "protocl action:"+actionName+", type:"+actionType);
		
		if(!actionName.equals("") && !actionType.equals(""))
		{
			BaseAction action = null;
			if(actionName.equals(LoginAction.TAG)){
				action = new LoginAction(context);
			} else if(actionName.equals(RegisterAction.TAG)){
				action = new RegisterAction(context);
			} else if(actionName.equals(FindPwdAction.TAG)){
				action = new FindPwdAction(context);
			} else if(actionName.equals(GetSensorAction.TAG)){
				action = new GetSensorAction();
			} else if(actionName.equals(GetConfigAction.TAG)){
				action = new GetConfigAction(context);
			} else if(actionName.equals(SetConfigAction.TAG)){
				action = new SetConfigAction(context);
			} else if(actionName.equals(ControlAction.TAG)){
				action = new ControlAction(context);
			} else if(actionName.equals(GetControllerStatusAction.TAG)){
				action = new GetControllerStatusAction();
			}
			
			if(action != null)
			{
				action.setType(actionType);
				httpResp = action.porcessAction(strBody);
			}
		}
		
		httpResp += "\n";
		Log.i(TAG, "return :" + httpResp);
		// 构造 http 响应消息
		return new NanoHTTPD.Response(httpResp);
	}
	
	// 解析http body
	private String parsebody(IHTTPSession session) {
		String body = "";
		try 
		{
			InputStream is = session.getInputStream();
			if (is == null) {
				Log.i(TAG, "session.getInputStream() is null!");
				return body;
			}
			
			long size = 0;
			Map<String, String> headers = session.getHeaders();
            if (headers.containsKey("content-length")) {
                size = Integer.parseInt(headers.get("content-length"));
            }
            
            if(size > 0)
            {
				// 假定消息不超过8192byte
				int bufsize = 8192;
				byte[] buf = new byte[bufsize];
				int rlen = is.read(buf, 0, (int)Math.min(size, bufsize));
				if (rlen <= 0) {
					Log.i(TAG, "http body read 0 byte!");
					return null;
				}
	            
				ByteArrayInputStream hbis = new ByteArrayInputStream(buf, 0, rlen);
				BufferedReader hin = new BufferedReader(new InputStreamReader(hbis));
				body = hin.readLine();
            }
			return body;
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} 
		return null;
	}
}
